<template>
  <div>
    <van-form validate-first @failed="onFailed" ref="form" @submit="submits">
      <!-- 通过 pattern 进行正则校验 -->
      <van-field
        v-model="username"
        name="pattern"
        label="用户名"
        placeholder="请输入账号"
        :rules="[{ pattern, message: '请输入正确内容' }]"
      />
      <van-field
        v-model="password"
        name="validator"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ validator, message: '请输入正确内容' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import Vue from 'vue'
// 这是vant 组件
import { Form, Field, Button, Toast } from 'vant'
Vue.use(Form)
Vue.use(Field)
Vue.use(Button)
Vue.use(Toast)
Toast.setDefaultOptions({ duration: 900 })
export default {
  data() {
    return {
      name: '',
      username: 'admin',
      password: '123456',
      pattern: /^[a-z]{5,12}$/
      // pattern2: /\d{6}/
    }
  },
  methods: {
    onFailed(errorInfo) {
      // console.log('failed', errorInfo)
      // if (errorInfo) {
      //   return console.log('验证错误')
      // }
      // console.log('验证成功')
      this.name = errorInfo
    },
    // 校验函数返回 true 表示校验通过，false 表示不通过
    validator(val) {
      return /\d{6}/.test(val)
    },
    // 发起验证的请求
    // async verifty() {
    //   const result = await this.$refs.loginonerules.validate(name)
    //   // console.log('11')
    //   // console.log(result)
    //   if (result) {
    //     console.log('验证失败')
    //   }
    // },
    // 只有验证通过了才能发起请求
    async submits(valus) {
      console.log('11')
      const { data: res } = await this.$http.post('login', {
        username: this.username,
        password: this.password
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return Toast.fail('登录失败')
      }
      // 设置token 令牌
      window.sessionStorage.setItem('token', res.data.token) // token 是键  res.data.token 是值
      // 自定义加载图标
      Toast.loading({
        message: '登录中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      // 登录成功后进行路由的跳转
      // setTimeout(this.push(), 5000)
      setTimeout(item => {
        this.$router.push('/home')
      }, 1000)
    }
  }
}
</script>

<style lang="less">
.van-field__control {
  border: 0 !important;
}
.van-field__label {
  display: flex;
  justify-content: center;
  align-items: center;
}
.van-field__control {
  margin-bottom: 0 !important;
  font-size: 13px;
}
.van-field__error-message {
  color: skyblue;
  font-size: 10px;
}
</style>
